package com.xhl.component.client.rocketmq;

import com.commons.tools.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Results;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author CazCen
 * @Date 2022/1/18 2:04
 */
@RestController
@RequestMapping("/mqProducer")
@Api("mq 发送消息")
public class MqProducerController {

    public static final Logger LOGGER = LoggerFactory.getLogger(MqProducerController.class);

    @Autowired
    private DefaultMQProducer defaultProducer;

    /**
     * 发送简单的MQ消息
     * @param msg
     * @return
     */
    @ApiOperation("发消息")
    @PostMapping("/send")
    public Result send(String msg) throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
        if (StringUtils.isEmpty(msg)) {
            return Result.ok();
        }
        LOGGER.info("发送MQ消息内容：" + msg);
        Message sendMsg = new Message("TestTopic", "TestTag", msg.getBytes());
        // 默认3秒超时
        SendResult sendResult = defaultProducer.send(sendMsg);
        LOGGER.info("消息发送响应：" + sendResult.toString());
        return Result.ok(sendResult);
    }

}
